<template>
  <div class="bg-white p-6 rounded-lg shadow">
    <div class="text-xl">流程定义</div>
    <!-- 搜索栏 -->
    <div class="mb-4">
      <el-form :model="queryForm" inline>
        <el-form-item label="流程名称">
          <el-input v-model="queryForm.name" placeholder="请输入流程名称" clearable/>
        </el-form-item>
        <el-form-item label="流程Key">
          <el-input v-model="queryForm.key" placeholder="请输入流程Key" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作栏 -->
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-lg font-semibold text-gray-800">流程定义管理</h2>
      <div class="flex gap-2">
        <el-button type="primary" icon="el-icon-refresh" @click="loadProcessDefinitions">刷新</el-button>
        <el-button type="success" icon="el-icon-plus" @click="showDeployDialog = true">部署流程</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="processDefinitions" stripe>
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="name" label="名称"/>
      <el-table-column prop="key" label="Key"/>
      <el-table-column prop="version" label="版本" width="80"/>
      <el-table-column prop="deploymentId" label="部署ID"/>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button @click="handleView(scope.row)" type="text" size="small">查看</el-button>
          <el-button @click="openStartDialog(scope.row)" type="text" size="small">发起流程</el-button>
          <el-button @click="handleDelete(scope.row)" type="danger" text size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 部署对话框 -->
    <el-dialog title="部署流程" v-model="showDeployDialog" width="600px">
      <el-form :model="deployForm" label-width="100px">
        <el-form-item label="流程名称" required>
          <el-input v-model="deployForm.name" placeholder="请输入流程名称"/>
        </el-form-item>
        <el-form-item label="流程Key" required>
          <el-input v-model="deployForm.key" placeholder="请输入流程Key"/>
        </el-form-item>
        <el-form-item label="BPMN文件" required>
          <el-input v-model="deployForm.bpmnXml" placeholder="请输入流程Key"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDeployDialog = false">取消</el-button>
        <el-button type="primary" @click="handleDeploy" :loading="loading">部署</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog title="流程详情" v-model="showViewDialog" width="800px">
      <div v-if="currentProcess">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="流程ID">{{ currentProcess.id }}</el-descriptions-item>
          <el-descriptions-item label="流程名称">{{ currentProcess.name }}</el-descriptions-item>
          <el-descriptions-item label="流程Key">{{ currentProcess.key }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ currentProcess.version }}</el-descriptions-item>
          <el-descriptions-item label="部署ID">{{ currentProcess.deploymentId }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentProcess.suspended ? 'danger' : 'success'">
              {{ currentProcess.suspended ? '已挂起' : '已激活' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 发起流程对话框 -->
    <el-dialog title="发起流程" v-model="showStartDialog" width="500px">
      <div v-if="currentProcess">
        <el-form :model="startForm" label-width="80px">
          <el-form-item label="流程名称">
            <el-input v-model="currentProcess.name"/>
          </el-form-item>
          <el-form-item label="业务编号">
            <el-input v-model="startForm.businessKey" placeholder="可选"/>
          </el-form-item>
          <el-form-item label="流程变量">
            <el-input v-model="startForm.variables" type="textarea" :rows="4"
                      placeholder='JSON格式，如：{"days": 3, "reason": "年假"}'/>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="showStartDialog = false">取消</el-button>
        <el-button type="primary" @click="handleStartProcess" :loading="loading.startProcess">
          发起流程
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from "axios";
import {API_BASE_URL} from "@/assets/_const";

// 数据
const processDefinitions = ref([])
const loading = ref(false)
const showViewDialog = ref(false)
const currentProcess = ref(null)

// 表单
const queryForm = reactive({
  name: '',
  key: ''
})

const showDeployDialog = ref(false)
const deployForm = reactive({
  name: '',
  key: '',
  bpmnXml: null
})

// 数据
const showStartDialog = ref(false)

const startForm = reactive({
  businessKey: '',
  variables: ''
})

// 方法
const loadProcessDefinitions = async () => {
  loading.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/api/model/getPage`);
    processDefinitions.value = response.data;
  } catch (error) {
    console.log(error);
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  loadProcessDefinitions()
}

const handleReset = () => {
  Object.assign(queryForm, {name: '', key: ''})
  loadProcessDefinitions()
}

const handleView = (row) => {
  currentProcess.value = row
  showViewDialog.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除该流程定义吗？', '警告', {type: 'warning'})
    // 调用删除API
    ElMessage.success('删除成功')
    await loadProcessDefinitions()
  } catch {
    // 用户取消
  }
}

const handleDeploy = async () => {
  if (!deployForm.name || !deployForm.key || !deployForm.bpmnXml) {
    ElMessage.warning('请填写完整信息')
    return
  }

  loading.value = true
  try {
    // 调用部署API
    const response = await axios.post(`${API_BASE_URL}/api/model/deployProcessModel`, deployForm);
    ElMessage.success('部署成功')
    showDeployDialog.value = false
    Object.assign(deployForm, {name: '', key: '', file: null})
    await loadProcessDefinitions()
  } catch (error) {
    ElMessage.error('部署失败')
  } finally {
    loading.value = false
  }
}

const openStartDialog = (row) => {
  currentProcess.value = row
  startForm.businessKey = ''
  startForm.variables = ''
  showStartDialog.value = true
}

const handleStartProcess = async () => {
  try {
    loading.startProcess = true

    const requestData = {
      processDefinitionKey: currentProcess.value.key,
      businessKey: startForm.businessKey || undefined
    }

    // 解析流程变量
    if (startForm.variables) {
      try {
        requestData.variables = JSON.parse(startForm.variables)
      } catch (e) {
        ElMessage.error('流程变量格式错误，请输入有效的JSON')
        return
      }
    }

    // 调用发起流程API
    await axios.post(`${API_BASE_URL}/api/process/exec/startProcess`, requestData)

    ElMessage.success('流程发起成功')
    showStartDialog.value = false
  } catch (error) {
    console.error('发起流程失败:', error)
    ElMessage.error('发起流程失败')
  } finally {
    loading.startProcess = false
  }
}
// 生命周期
onMounted(() => {
  loadProcessDefinitions()
})
</script>